package com.zsml.customdialog;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Button btn_dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_dialog = (Button) findViewById(R.id.btn_dialog);
        btn_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCustomDialog();
            }
        });
    }

    private void showCustomDialog() {
        final Dialog customDialog = new Dialog(this, R.style.Dialog);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_custom, null);
        TextView btn_update = (TextView) dialogView.findViewById(R.id.tv_update);
        TextView btn_cancel = (TextView) dialogView.findViewById(R.id.tv_cancel);
        //将自定义布局加载到dialog上
        customDialog.setContentView(dialogView);

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialog.cancel();
            }
        });
        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "点击了确定", Toast.LENGTH_SHORT).show();
            }
        });

        //设置点击dialog外是否可以取消
        customDialog.setCancelable(false);
        customDialog.show();


        //获得dialog的window窗口
        Window window = customDialog.getWindow();
        //设置dialog在屏幕中间
        window.setGravity(Gravity.CENTER);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //宽度设置为屏幕的0.7
        Display defaultDisplay = getWindowManager().getDefaultDisplay();//
        lp.width = (int) (defaultDisplay.getWidth() * 0.7);
        //将设置好的属性set回去
        window.setAttributes(lp);
    }
}
